#include "SubjectManagerWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QLabel>
#include <QHeaderView>
#include <QMessageBox>
#include <QScrollArea>

SubjectManagerWidget::SubjectManagerWidget(QWidget *parent) : QWidget(parent), m_optionalExpanded(false) {
    // 创建主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    // 设置必填字段
    setupRequiredFields();

    // 顶部表单布局（必填项）
    QGroupBox *requiredGroup = new QGroupBox("必填项（基础人口统计学信息）", this);
    QFormLayout *requiredLayout = new QFormLayout(requiredGroup);
    requiredLayout->addRow("姓名:", m_nameEdit);
    requiredLayout->addRow("性别:", m_genderCombo);
    requiredLayout->addRow("年龄:", m_ageSpin);

    // 选填项按钮
    m_optionalButton = new QPushButton("展开选填项 ▼", this);
    connect(m_optionalButton, &QPushButton::clicked, this, &SubjectManagerWidget::onOptionalButtonClicked);

    // 选填项区域（初始隐藏）
    m_optionalWidget = new QWidget(this);
    m_optionalWidget->setVisible(false);
    setupOptionalFields();

    // 添加按钮
    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_addButton);

    // 表格用于显示被试列表
    m_table = new QTableWidget(this);
    m_table->setColumnCount(4);
    QStringList headers;
    headers << "ID" << "姓名" << "性别" << "年龄";
    m_table->setHorizontalHeaderLabels(headers);
    m_table->horizontalHeader()->setStretchLastSection(true);
    m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 布局组合
    mainLayout->addWidget(requiredGroup);
    mainLayout->addWidget(m_optionalButton);
    mainLayout->addWidget(m_optionalWidget);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(m_table);

    setLayout(mainLayout);
}

void SubjectManagerWidget::setupRequiredFields() {
    // 创建必填控件
    m_nameEdit = new QLineEdit(this);
    m_nameEdit->setPlaceholderText("请输入姓名");

    m_genderCombo = new QComboBox(this);
    m_genderCombo->addItems(QStringList() << "男" << "女" << "其他");

    m_ageSpin = new QSpinBox(this);
    m_ageSpin->setRange(0, 120);
    m_ageSpin->setValue(25);

    m_addButton = new QPushButton("新增被试", this);
    connect(m_addButton, &QPushButton::clicked, this, &SubjectManagerWidget::onAddButtonClicked);
}

void SubjectManagerWidget::setupOptionalFields() {
    QVBoxLayout *optionalLayout = new QVBoxLayout(m_optionalWidget);

    // 1. 核心社会人口学变量
    QStringList sociodemographicFields = {
        "受教育程度（学历水平）",
        "职业（包括就业状态）",
        "婚恋状态",
        "住址（城乡分布/地区）",
        "人种/民族"
    };
    QWidget *sociodemographicWidget = createCategoryWidget("核心社会人口学变量", sociodemographicFields);
    optionalLayout->addWidget(sociodemographicWidget);
    m_categoryWidgets["核心社会人口学变量"] = sociodemographicWidget;

    // 2. 社会经济地位相关
    QStringList socioeconomicFields = {
        "收入水平/家庭年收入",
        "社会阶层自我认同",
        "家庭成员数量/家庭结构"
    };
    QWidget *socioeconomicWidget = createCategoryWidget("社会经济地位相关", socioeconomicFields);
    optionalLayout->addWidget(socioeconomicWidget);
    m_categoryWidgets["社会经济地位相关"] = socioeconomicWidget;

    // 3. 生活方式与健康变量
    QStringList lifestyleFields = {
        "是否抽烟",
        "是否喝酒",
        "睡眠时长",
        "是否近视"
    };
    QWidget *lifestyleWidget = createCategoryWidget("生活方式与健康变量", lifestyleFields);
    optionalLayout->addWidget(lifestyleWidget);
    m_categoryWidgets["生活方式与健康变量"] = lifestyleWidget;

    // 4. 健康与生活质量
    QStringList healthFields = {
        "身体健康状况自评",
        "心理健康状况自评",
        "体育锻炼频率",
        "BMI指数/身高体重"
    };
    QWidget *healthWidget = createCategoryWidget("健康与生活质量", healthFields);
    optionalLayout->addWidget(healthWidget);
    m_categoryWidgets["健康与生活质量"] = healthWidget;

    // 5. 个人特质变量
    QStringList personalityFields = {
        "MBTI人格",
        "是否左撇子",
        "爱好"
    };
    QWidget *personalityWidget = createCategoryWidget("个人特质变量", personalityFields);
    optionalLayout->addWidget(personalityWidget);
    m_categoryWidgets["个人特质变量"] = personalityWidget;

    // 6. 社会关系与网络
    QStringList socialFields = {
        "社交媒体使用情况",
        "社会支持网络规模",
        "社区参与度"
    };
    QWidget *socialWidget = createCategoryWidget("社会关系与网络", socialFields);
    optionalLayout->addWidget(socialWidget);
    m_categoryWidgets["社会关系与网络"] = socialWidget;

    // 7. 文化与认同相关
    QStringList culturalFields = {
        "宗教信仰",
        "政治倾向",
        "语言使用情况"
    };
    QWidget *culturalWidget = createCategoryWidget("文化与认同相关", culturalFields);
    optionalLayout->addWidget(culturalWidget);
    m_categoryWidgets["文化与认同相关"] = culturalWidget;

    // 8. 价值观与态度
    QStringList valueFields = {
        "生活满意度",
        "对社会问题的关注度",
        "核心价值观倾向"
    };
    QWidget *valueWidget = createCategoryWidget("价值观与态度", valueFields);
    optionalLayout->addWidget(valueWidget);
    m_categoryWidgets["价值观与态度"] = valueWidget;
}

QWidget* SubjectManagerWidget::createCategoryWidget(const QString &title, const QStringList &fields) {
    QGroupBox *groupBox = new QGroupBox(title, this);
    QFormLayout *formLayout = new QFormLayout(groupBox);

    m_optionalFields[title] = QMap<QString, QWidget*>();

    for (const QString &field : fields) {
        QLineEdit *lineEdit = new QLineEdit(this);
        lineEdit->setPlaceholderText("请输入" + field);
        formLayout->addRow(field + ":", lineEdit);

        // 存储字段控件引用
        m_optionalFields[title][field] = lineEdit;
    }

    return groupBox;
}

void SubjectManagerWidget::onOptionalButtonClicked() {
    m_optionalExpanded = !m_optionalExpanded;
    m_optionalWidget->setVisible(m_optionalExpanded);

    if (m_optionalExpanded) {
        m_optionalButton->setText("收起选填项 ▲");
    } else {
        m_optionalButton->setText("展开选填项 ▼");
    }
}

void SubjectManagerWidget::onAddButtonClicked() {
    QString name = m_nameEdit->text().trimmed();
    QString gender = m_genderCombo->currentText();
    int age = m_ageSpin->value();

    if (name.isEmpty()) {
        QMessageBox::warning(this, "提示", "姓名不能为空");
        return;
    }

    // 收集选填数据
    QMap<QString, QString> optionalData = collectOptionalData();

    // 发射信号通知MainWindow/Database添加被试
    emit subjectAdded(name, gender, age, optionalData);

    // 清空输入
    m_nameEdit->clear();
    m_ageSpin->setValue(25);

    // 清空所有选填字段
    for (auto categoryIt = m_optionalFields.begin(); categoryIt != m_optionalFields.end(); ++categoryIt) {
        for (auto fieldIt = categoryIt.value().begin(); fieldIt != categoryIt.value().end(); ++fieldIt) {
            QLineEdit *lineEdit = qobject_cast<QLineEdit*>(fieldIt.value());
            if (lineEdit) {
                lineEdit->clear();
            }
        }
    }
}

QMap<QString, QString> SubjectManagerWidget::collectOptionalData() {
    QMap<QString, QString> data;

    for (auto categoryIt = m_optionalFields.begin(); categoryIt != m_optionalFields.end(); ++categoryIt) {
        QString category = categoryIt.key();

        for (auto fieldIt = categoryIt.value().begin(); fieldIt != categoryIt.value().end(); ++fieldIt) {
            QString fieldName = fieldIt.key();
            QLineEdit *lineEdit = qobject_cast<QLineEdit*>(fieldIt.value());

            if (lineEdit && !lineEdit->text().isEmpty()) {
                // 使用类别和字段名作为键
                data[category + ":" + fieldName] = lineEdit->text();
            }
        }
    }

    return data;
}

void SubjectManagerWidget::reloadSubjectList(const QList<QVariantList> &subjects) {
    m_table->setRowCount(subjects.size());
    for (int i = 0; i < subjects.size(); ++i) {
        const QVariantList &row = subjects[i];
        // row顺序: [id, name, gender, age]
        for (int j = 0; j < row.size(); ++j) {
            QTableWidgetItem *item = new QTableWidgetItem(row[j].toString());
            m_table->setItem(i, j, item);
        }
    }
}
